"use client";
import { motion } from 'framer-motion';
import { use, useEffect, useMemo, useState } from 'react'

import { BlogPostProps } from "@/lib/getBlogPosts";

import { Affix, Breadcrumb, Button, ConfigProvider, Menu, MenuProps, theme } from 'antd';

import MdDetail from '@/components/MdDetail'

// i18n
import "../locales/i18n";
import { useTranslation } from 'react-i18next';
import LocalePicker from './locale-picker';

const colorPrimary = "#FF9900"
import React from 'react';
import { Flex, Layout } from 'antd';
import Logo from './logo';

const { Header, Footer, Sider, Content } = Layout;

export default function MdList({ mdFiles }: { mdFiles: BlogPostProps[] }) {
  const { t } = useTranslation();
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  // 菜单配置对象
  const menuConfigList = [
    { label: '主页', routePath: '/home', mdFileName: 'home' },
    { label: '版本', routePath: '/version', mdFileName: 'version' },
    { label: t('sys.menu.dashboard'), routePath: '/dashboard', mdFileName: 'dashboard-workbench' },
    {
      label: t('sys.menu.user.index'),
      children: [
        { label: t('sys.menu.user.profile'), routePath: '/user/profile/detail', mdFileName: 'user-profile' },
        { label: t('sys.menu.user.account'), routePath: '/user/account', mdFileName: 'user-account' }]
    },
    {
      label: t('sys.menu.system.index'),
      children: [
        { label: t('sys.menu.system.role'), routePath: '/system/role', mdFileName: 'system-role' },
        { label: t('sys.menu.system.user'), routePath: '/system/user', mdFileName: 'system-user' },
        //{ label: t('sys.menu.system.user-detail'), routePath: '/system/user/detail', mdFileName: 'system-userdetail' },
        { label: t('sys.menu.system.data-enum'), routePath: '/system/data-enum', mdFileName: 'system-data-enum' },
        { label: t('file.menu.file'), routePath: '/system/index', mdFileName: 'system-file' },
        { label: t('order.menu.index'), routePath: '/system/order', mdFileName: 'system-order' },
        { label: t('notification.menu.index'), routePath: '/system/notification', mdFileName: 'system-notification' },
        //{ label: t('sys.menu.system.tenant'), routePath: '/system/tenant/index', mdFileName: 'system-' },
      ]
    },
    {
      label: t('domain.menu.index'),
      children: [
        { label: t('domain.menu.settings'), routePath: '/domain/domain-settings', mdFileName: 'domain-settings' },
        { label: t('domain.menu.organization'), routePath: '/domain/organization', mdFileName: 'domain-organization' },
        { label: t('domain.menu.domainuser'), routePath: '/domain/domain-user', mdFileName: 'domain-domainuser' },
        { label: t('library.menu.defect'), routePath: '/domain/defect', mdFileName: 'library-defect' },
        { label: t('domain.menu.factory'), routePath: '/domain/factory', mdFileName: 'domain-factory' },
        { label: t('domain.menu.contact'), routePath: '/domain/contact', mdFileName: 'domain-contact' },
        { label: t('library.menu.question-template'), routePath: '/domain/question-template', mdFileName: 'library-questiontemplate' },
        { label: t('library.menu.questionnaire'), routePath: '/domain/questionnaire', mdFileName: 'library-questionnaire' },
      ]
    },
    { label: t('library.menu.checklist'), routePath: '/checklist', mdFileName: 'library-workinstruction' },
    { label: t('checklist.menu.checklist-config'), routePath: '/checklist-config/detail', mdFileName: 'library-wi_config' },
    { label: t('purchase-order.menu.purchase-order'), routePath: '/purchase-order', mdFileName: 'work-purchaseorder' },
    { label: t('purchase-order.menu.purchase-order-detail'), routePath: '/purchase-order/detail', mdFileName: 'work-purchaseorder_detail' },
    { label: t('inspection.menu.inspection'), routePath: '/inspection', mdFileName: 'work-inspection' },
    { label: t('inspection.menu.inspection-detail'), routePath: '/inspection/detail', mdFileName: 'work-inspection_detail' },
    { label: t('inspection.menu.inspection-calendar'), routePath: '/calendar', mdFileName: 'work-inspection_calendar' },
    { label: t('inspection.menu.inspection-simplify-detail'), routePath: '/inspection-simplify/detail', mdFileName: 'work-inspectionsimplify' },
    { label: t('report.menu.report'), routePath: '/report', mdFileName: 'work-report' },
    { label: t('report.menu.report-detail'), routePath: '/report/detail', mdFileName: 'work-reportdetail' },


    //{ label: t('report.menu.report-detail'), routePath: 'report-simplify/detail', mdFileName: 'report_simplify' },
    //{ label: t(''), routePath: '', mdFileName: '' },
    // {
    //   label: 'ValueRecord',
    //   children: [
    //     { label: t('value-record.menu.value-record'), routePath: '/index', mdFileName: 'valuerecord-value' }
    //   ]
    // }

  ]

  const [matchedMenuItem, setMatchedMenuItem] = useState<any>(undefined)

  // 面包屑
  const layoutBreadcrumbItem = { title: 'Home' }
  const [breadcrumbItems, setBreadcrumbItems] = useState<any[]>([
    layoutBreadcrumbItem
  ])

  const [isAsideCollapsed, setIsAsideCollapsed] = useState(false)


  const toggleCollapsed = () => {
    setIsAsideCollapsed(!isAsideCollapsed);
  };

  const [currentMdFile, setcurrentMdFile] = useState<BlogPostProps>()
  const siderStyle: React.CSSProperties = {
    overflow: 'auto',
    height: '100vh',
    position: 'sticky',
    insetInlineStart: 0,
    top: 0,
    bottom: 0,
    scrollbarWidth: 'thin',
    scrollbarGutter: 'stable',
    background: colorBgContainer,
  };
  useEffect(() => {
    setDefaultSelectdMd()
  }, []);




  function setDefaultSelectdMd() {
    // 获取当前网址参数
    if (typeof window !== 'undefined') {
      const url = new URL(window.location.href);
      const routePathParam = url.searchParams.get('routePath');
      if (routePathParam) {
        // 根据当前路由名称快捷打开对应md
        var matchedMenuItem: any = undefined;
        for (var i = 0; i < menuConfigList.length; i++) {
          var item = menuConfigList[i];
          if (item.routePath === routePathParam) {
            matchedMenuItem = item;
            break;
          }
          if (item.children) {
            var currentChildren = item.children.find((item2: any) => item2.routePath === routePathParam)
            if (currentChildren) {
              matchedMenuItem = currentChildren;
              break;
            }
          }
        }
        // 优先匹配地址路由对应的md，匹配不到则默认第一个
        if (matchedMenuItem) {
          setMatchedMenuItem(matchedMenuItem)
        }
        else {
          setMatchedMenuItem(menuConfigList[0])
        }
      }
      else {
        setMatchedMenuItem(menuConfigList[0])
      }
    }
  }
  useEffect(() => {
    if (matchedMenuItem) {
      // 设置当前显示的md
      setSelectdMd(matchedMenuItem.routePath, matchedMenuItem.mdFileName);
    }
  }, [matchedMenuItem]);


  useEffect(() => {
    const hash = window.location.hash;
    if (hash) {
      setTimeout(() => {
        const decodedId = decodeURIComponent(hash.slice(1));
        const target = document.getElementById(decodedId);
        if (target) {
          target.scrollIntoView({ behavior: 'smooth' });
        }
      }, 500);
    }
  }, []);

  // 设置当前显示md
  function setSelectdMd(path: string, mdFileName: string) {
    var paths = path.split('/').filter(item => item !== '').map((item, index) => ({ title: item }));
    setBreadcrumbItems([
      layoutBreadcrumbItem,
      ...paths
    ])
    // 小屏幕点击自动隐藏
    if (window.innerWidth <= 768) {
      setIsAsideCollapsed(false)
    }
    // 设置显示md文件
    const fitMd = mdFiles.find((item) => item.slug === mdFileName)
    fitMd && setcurrentMdFile(fitMd)
  }

  function getMenuItem(key: string) {
    if (menuConfigList) {
      var indexes = key.split('-')
      var menuIndex = parseInt(indexes[0]);
      var subMenuIndex = -1;
      if (indexes.length > 1) {
        subMenuIndex = parseInt(indexes[1]);
      }
      var parentMenuItem = menuConfigList[menuIndex - 1];

      if (parentMenuItem?.children && subMenuIndex > 0) {
        var menuItem = parentMenuItem?.children[subMenuIndex - 1]
        console.warn('click ', menuItem);
        return menuItem
      }
      else {
        if (parentMenuItem?.routePath) {
          return parentMenuItem
        }
      }
    }
  }


  function getMenuKey(menu: any): string {
    if (menuConfigList) {
      var parentItem = menuConfigList.find((item: any) => item.routePath === menu.routePath);
      var parentIndex = parentItem === undefined ? -1 : menuConfigList.indexOf(parentItem);
      if (parentIndex > -1) {
        return `${parentIndex + 1}`;
      }
      for (var i = 0; i < menuConfigList.length; i++) {
        var item = menuConfigList[i];
        if (item.children) {
          var child = item.children.find((child: any) => child.routePath === menu.routePath);
          var childIndex = child === undefined ? -1 : item.children.indexOf(child);
          if (childIndex > -1) {
            return `${i + 1}-${childIndex + 1}`;
          }
        }
      }
    }
    return "1";
  }

  const onClick: MenuProps['onClick'] = (e) => {
    var menu = getMenuItem(e.key)
    setMatchedMenuItem(menu);
  };


  return (
    <Layout hasSider>
      <Sider style={siderStyle}
        breakpoint="lg"
        collapsedWidth="0"
      >
        <div className="demo-logo-vertical" />
        <div style={{ marginTop: '64px' }}>

          {/* <Button type="primary" onClick={toggleCollapsed} style={{ marginBottom: 16 }}>
            {isAsideCollapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
          </Button> */}
          <Menu
            style={{ border: 0 }}
            onClick={onClick}
            selectedKeys={[matchedMenuItem ? getMenuKey(matchedMenuItem) : '1']}
            mode="inline"
            inlineCollapsed={isAsideCollapsed}
            items={menuConfigList.map((item, index) => ({
              key: index + 1,
              label: item.label,
              children: item.children?.map((child, childIndex) => ({
                key: `${index + 1}-${childIndex + 1}`,
                label: <span >{child.label}</span>,
                routePath: child.routePath,
                mdFileName: child.mdFileName
              }))

            }))}
          />
        </div>

      </Sider>
      <Layout>
        <Header style={{ position: 'sticky', padding: 0, top: 0, zIndex: 1, background: colorBgContainer }} >
          <div className='flex justify-between items-center px-4'>
            <div className='flex items-center'>
              <Logo></Logo>
              <h1 className='text-xl font-semibold'> Help And Support</h1>
            </div>
            <LocalePicker></LocalePicker>

          </div>

        </Header>
        <Content style={{ margin: '24px 16px 0', overflow: 'initial' }}>
          <div className='shadow'
            style={{
              background: colorBgContainer,
              borderRadius: borderRadiusLG,
            }}
          >
            <Affix offsetTop={62}>
              <div style={{ padding: ' 16px 24px', background: colorBgContainer }}>
                <Breadcrumb
                  items={breadcrumbItems}
                />
              </div>
            </Affix>

            <div className='p-6'>
              <MdDetail mdFile={currentMdFile} />
            </div>



          </div>
        </Content>
        <Footer style={{ textAlign: 'center' }}>
          QCDIY ©{new Date().getFullYear()} Created by V-Trust Group
        </Footer>
      </Layout>
    </Layout>

  );
}